import React, { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { AtModal } from 'taro-ui';
import {View,Image,Text, Canvas, Swiper, SwiperItem} from '@tarojs/components'
import YiCode from '@/components/yi-code'
import "taro-ui/dist/style/components/modal.scss";
import './index.scss'

export default function OpenCard() {
  const [cardList, setcardList] = useState([])
  const [curCard,setCurCard] = useState(0)
  const [curSelect,setCurSelect] = useState(0)
  const [isAgree,setIsAgree] = useState(false)
  const [showModal,setShowModal] = useState(false)
  const [captcha,setCaptcha] = useState('')
  const [messageInfo,setMessageInfo] = useState('')
  useEffect(()=>{
    const {router} = Taro.getCurrentInstance()
    Taro.$get('/cinema-app/api/dx/card',{
      cinemaId:Taro.getStorageSync('merchantId'),
      latitude:Taro.getStorageSync('position')?.latitude,
      longitude:Taro.getStorageSync('position')?.longitude
    }).then(res=>{
      if(res.code == '1'){
        setcardList(res.content)
        if(router.params.cardId && res.content.length){
          setCurCard(res.content?.findIndex(ret=>ret.id == router.params.cardId))
        }
      }
    })
  },[])
  const handlePay =(content,orderId)=>{
    if(process.env.TARO_ENV == 'tt'){
      tt.pay({
        orderInfo: {
          order_id:content.data.orderId,
          order_token: content.data.orderToken
        },
        service: 5,
        _debug:1,
        success:res=>{
          if(res.code == 0){
            Taro.navigateBack()
          }
        },
        fail:err=>{
          Taro.$toast('支付失败')
        }
      });
      return;
    }
    if(process.env.TARO_ENV == 'h5' && navigator.userAgent.toLowerCase().match(/MicroMessenger/i)=="micromessenger"){
      WeixinJSBridge.invoke('getBrandWCPayRequest', {
        "appId": Taro.$mpAppid,
        "timeStamp": content.timeStamp,   
        "nonceStr": content.nonceStr,  
        "package": content.packageStr,
        "signType": content.signType,    
        "paySign":content.paySign
      },(result) => {
        if(result.err_msg == "get_brand_wcpay_request:cancel"){
          Taro.$toast('取消支付','error')
        }else{
          Taro.navigateBack()
        }
      });
      return;
    }
    Taro.requestPayment({
      timeStamp: content.timeStamp,
      nonceStr: content.nonceStr,
      package: content.package,
      signType: content.signType,
      paySign: content.paySign,
      success:res=>{
        Taro.navigateBack()
      },
      fail:err=>{
        Taro.$toast('支付失败')
      }
    })
  }
  return (
    <View className='page-open-card'>
      {cardList.length?<>
      <Swiper className='card-swiper' current={curCard} onChange={e=>{
        setCurCard(e.detail.current)
      }}>
        {cardList.map((item,idx)=>{
          return <SwiperItem key={item.id} className='swiper-item'>
            <View className="card-header" style={{background:item.cardStyle=='1'?item.cardColour:`url(${item.cardUrl})`}}>
              <View className="item-icon">开卡特惠</View>
              <View className="item-header">
                <Image className='header-img' src={item.logoUrl || Taro.getStorageSync('appConfig')?.iconUrl}></Image>
                {item.levelName}
              </View>
              <View className="item-desc">
                <View className="desc-p">
                  {item.cardTypeDesc} <Text style={{fontSize:'12PX',opacity:.8}}>{item.recommend}</Text>
                </View>
                <View>开卡充值：¥{item.price}</View>
                {/* <View onClick={e=>{
                  if(item.explainRemark){
                    Taro.showModal({
                      title:"使用说明",
                      content:item.explainRemark
                    })
                  }
                }}>使用说明</View> */}
              </View>
            </View>
            {/* <View className="card-select">
              <View className="card-h2">选择充值面额 <Text className='h2-span'>（不同充值档位赠送不同礼品）</Text></View>
              <View className="select-list">
                {item.configPackages?.map((res,index)=>{
                  return <View key={index} className={`list-item ${curSelect == index?'active':''}`} onClick={()=>{setCurSelect(index)}}>
                    <View className="item-h2">{res.totalPrice}元</View>
                    到账{res.totalPayment}元
                  </View>
                })}
              </View>
            </View> */}
            {item.configPackages[curSelect]?.coupons && item.configPackages[curSelect].coupons?.length?
            <View className="card-gift">
              <View className="card-h2">开卡赠券活动 ({item.configPackages[curSelect].coupons?.length}张)</View>
              <View className="gift-list">
                {item.configPackages[curSelect].coupons.map((res)=>{
                  return <View key={res.id} className="list-item">
                    <View className="item-header">
                      <View className="header-info">
                        <View className="info-h2 dot2">{res.couponTypeDesc?<Text className='h2-span'>{res.couponTypeDesc}</Text>:null}{res.couponName}</View>
                        {res.effectEndDate?<View className="info-p">有效期至 {res.effectEndDate}</View>:null}
                      </View>
                      <View className="header-price">
                        <View className="price-info"><Text style={{fontSize:10,fontWeight:400}}>￥</Text>{res.couponFace}</View>
                        {res.threshold == '有门槛'?res.thresholdValue*1>0?`满${res.thresholdValue}减${res.couponFace}`:'':'无门槛'}
                      </View>
                    </View>
                    <View className="item-footer">
                      {res.couponInfo || ' '}
                      <View className="footer-button">赠送 {res.giveAmount} 张</View>
                    </View>
                  </View>
                })}
              </View>
            </View>:null}
            {item.memberEquityList?.length?
            <View className="card-equity">
              <View className="card-h2">电影卡权益</View>
              <View className="equity-list">
                {item.memberEquityList.map((res,idx)=>{
                  return <View className="list-item" key={idx}>
                  <Image src={res.equityIconPath} className='item-img'></Image>
                  <View className="item-info">
                    <View className="info-h2">{res.displayName}</View>
                    {res.equityIntroduction}
                  </View>
                </View>
                })}
              </View>
            </View>:null}
            <View className="card-notice">
              <View className="card-h2">开卡须知</View>
              <View className="notice-list">
                <View className="list-item" dangerouslySetInnerHTML={{__html:item.cardNote}}></View>
              </View>
            </View>
            {item.cinemasJsonDtos.length?
            <View className="card-equity card-cinema">
              <View className="card-h2">适用影院</View>
              <View className="equity-list">
                {item.cinemasJsonDtos?.slice(0,3).map((res,idx)=>{
                  return <View className="list-item" key={idx}>
                    <View className="item-info">
                      <View className="info-h2">{res.cinemaNickName}</View>
                      <View className="info-p">
                        <View className="address dot">{res.address}</View>
                        {res.distance?<View className="span">{res.distance}</View>:null}
                      </View>
                    </View>
                  </View>
                })}
                <View className="cinema-more" onClick={e=>{
                  let cinemaIds = []
                  item.cinemasJsonDtos.map(ret=>{
                    cinemaIds.push(ret.cinemaId)
                  })
                  Taro.setStorageSync('cinemaIds',cinemaIds)
                  Taro.navigateTo({
                    url:`/mainPages/apply-cinema/index`
                  })
                }}>查看更多适用影院(共{item.cinemasJsonDtos.length}家)</View>
              </View>
            </View>:null}
          </SwiperItem>
        })}
      </Swiper>

      <View className="card-footer">
        <View className="footer-agree">
          {isAgree?<Image onClick={()=>{
            setIsAgree(false)
          }} className='agree-img' src={require('@/images/mine/radio-on.svg')}></Image>:<Image onClick={()=>{
            setIsAgree(true)
          }} className='agree-img' src={require('@/images/mine/radio.svg')}></Image>}
          已阅读并同意<Text onClick={()=>{
            
          }}>《电影卡协议》</Text>
        </View>
        <View className="footer-button" onClick={()=>{
          if(!isAgree){
            Taro.showToast({
              title:'请先已阅读并同意电影卡协议',
              icon:'none'
            })
            return
          }
          setShowModal(true)
        }}>立即开通</View>
      </View>
      <AtModal className="card-modal" isOpened={showModal} onClose={()=>{setShowModal(false)}}>
        <View className="modal-header">
          <View className='at-icon at-icon-close' onClick={()=>{setShowModal(false)}}></View>
          <View className="header-h2">设置卡密码</View>
          <View></View>
        </View>
        {showModal?
        <View className="modal-main">
          <View className="main-span" style={{marginBottom:'24px'}}>为了保证你的账号安全，请设置您的卡密码后进行下一步操作。</View>
          <YiCode isFocus inputType='password' value={captcha} onConfirm={(code) => {
            setCaptcha(code)
          }} />
          {messageInfo?<View className="main-info"><Text style={{marginRight:'4px'}} className='at-icon at-icon-alert-circle'></Text>{messageInfo}</View>:null}
        </View>:null}
        <View className="modal-footer">
          <View className="footer-go" onClick={()=>{
            Taro.$post('/cinema-app/api/dx/card/openCard',{
              "cardLevelConfigId": cardList[curCard]?.id,
              "cardLevelName": cardList[curCard]?.levelName,
              // "configPackageId":cardList[curCard].configPackages[curSelect]?.id || '0',
              "cinemaId": Taro.getStorageSync('merchantId'),
              "mobile": Taro.getStorageSync('user')?.mobile,
              "password": captcha
            }).then(async res=>{
              if(res.code == '1'){
                Taro.showLoading({title:'加载中...'})
                let data = {
                  "appId": Taro.$mpAppid,
                  "channelType": "WXPAY",
                  "openId": await Taro.getOpenId(),
                  "orderId": res.content.orderId
                }
                Taro.$post('/order/users/orders/pay',data,'1').then(ret=>{
                  if(res.code == '1'){
                    setShowModal(false)
                    handlePay(ret.content,res.content.orderId)
                  }
                })
              }else{
                setMessageInfo(res.message || '开卡失败')
              }
            })
          }}>确定购买&nbsp;¥{cardList[curCard]?.price}</View>
        </View>
      </AtModal>
      </>:<View className='var-empty'>暂时没有电影卡可以买哦~</View>}
    </View>
  )
}
